package com.example.lobby.grpc;

import com.example.common.grpc.GrpcMessageBuilder;
import com.example.common.grpc.ServerIdGenerator;
import com.example.game.LoginRequest;
import com.example.game.LoginResponse;
import com.example.game.UserInfo;
import com.example.game.proto.internal.*;
import com.google.protobuf.InvalidProtocolBufferException;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: Allen
 * @create: 2025/7/3 16:43
 * @description:
 **/
@Slf4j
@GrpcService
@Service
public class GrpcServiceImpl extends GrpcServiceGrpc.GrpcServiceImplBase {

    @Autowired
    private SeverGrpcClient serverClient;

    @Autowired
    private ServerIdGenerator serverIdGenerator;

    private ExecutorService executors = Executors.newFixedThreadPool(10);

    @Override
    public void heartbeat(SrvReq request, StreamObserver<SrvResp> responseObserver) {
        SrvResp build = SrvResp.newBuilder().setRet(0).build();
        responseObserver.onNext(build);
        responseObserver.onCompleted();
    }

    @Override
    public void process(SrvReq request, StreamObserver<SrvResp> responseObserver) {
        try {
            log.info("收到处理请求: id={}, code={}, sid={}, userId={}",
                    request.getId(), request.getCode(), request.getSid(),
                    request.getUserId());



            // 根据协议号处理不同的业务逻辑
            SrvResp response = handleProcessRequest(request);
            responseObserver.onNext(Objects.requireNonNullElseGet(response, () -> GrpcMessageBuilder.buildSuccessResp(serverIdGenerator.getServerId(), request.getCode())));
            responseObserver.onCompleted();



            log.debug("处理请求响应发送成功: id={}, code={}", request.getId(), request.getCode());
        } catch (Exception e) {
            log.error("处理请求失败: id={}, code={}", request.getId(), request.getCode(), e);

            SrvResp errorResponse = GrpcMessageBuilder.buildErrorRespFromReq(
                    request, -1, "Gate service error: " + e.getMessage());

            responseObserver.onNext(errorResponse);
            responseObserver.onCompleted();
        }
    }


    /**
     * 根据协议号处理不同的业务逻辑
     *
     * @param request 请求消息
     * @return 响应消息
     */
    private SrvResp handleProcessRequest(SrvReq request) {
        int code = request.getCode();

        switch (code) {
            case 2001: // 用户登录
                return handleUserLogin(request);
            case 2002: // 用户登录
                handleUserLogin1(request);
                return null;
            default:
                log.warn("未知的协议号: code={}", code);
                return GrpcMessageBuilder.buildErrorRespFromReq(
                        request, -1001, "Unknown protocol code: " + code);
        }
    }


    /**
     * 处理用户登录
     */
    private SrvResp handleUserLogin(SrvReq request) {
        log.info("处理用户登录请求: userId={}", request.getUserId());

        // 这里可以添加实际的登录逻辑
        // 例如：验证用户信息、创建会话等
        try {
            LoginRequest login = LoginRequest.parseFrom(request.getBody());
            log.info("处理用户登录请求 userId:{},token:{}", login.getUserId(), login.getToken());

            int serverId = serverIdGenerator.getServerId();
            UserInfo userInfo = UserInfo.newBuilder().setUserId(login.getUserId()).setUsername("下雨"+serverId).setLevel(123).setCoins(100).build();
            LoginResponse response = LoginResponse.newBuilder().setSuccess(true).setUserInfo(userInfo).build();
            return GrpcMessageBuilder.buildSuccessRespFromReq(request, response.toByteArray());


        } catch (InvalidProtocolBufferException e) {
            throw new RuntimeException(e);
        }
    }


    private void handleUserLogin1(SrvReq request) {
        log.info("处理用户登录请求: userId={}", request.getUserId());

        // 这里可以添加实际的登录逻辑
        // 例如：验证用户信息、创建会话等
        try {
            LoginRequest login = LoginRequest.parseFrom(request.getBody());
            log.info("处理用户登录请求 userId:{},token:{}", login.getUserId(), login.getToken());
            int serverId = serverIdGenerator.getServerId();
            UserInfo userInfo = UserInfo.newBuilder().setUserId(login.getUserId()).setUsername("下雨"+serverId).setLevel(123).setCoins(100).build();
            LoginResponse response = LoginResponse.newBuilder().setSuccess(true).setUserInfo(userInfo).build();
            serverClient.callServiceByServerId(request.getSid(),2002, request.getUserId(), response.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
